package com.yb.guigu.pick.security.provider;

import com.yb.guigu.pick.security.bean.GuiguUsernamePasswordAuthenticationToken;
import com.yb.guigu.pick.security.bean.GuiguPickUser;
import com.yb.guigu.pick.security.encoder.GuiguPasswordEncoder;
import com.yb.guigu.pick.security.service.IGuiguPickUserDetailsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 * Copyright (C), 2022-2023, 姚兵
 * Author: 32210
 * Date: 2023/5/31 14:18
 * FileName: GuiguPickUserPasswordAuthenticationProvider
 * Description:
 */

@Component
@Slf4j
public class GuiguPickUserPasswordAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    IGuiguPickUserDetailsService userDetailService;

    @Autowired
    GuiguPasswordEncoder guiguPasswordEncoder;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        GuiguUsernamePasswordAuthenticationToken authenticationToken= (GuiguUsernamePasswordAuthenticationToken) authentication;

        GuiguPickUser guiguPickUser = authenticationToken.getGuiguPickUser();


        GuiguPickUser userDetails = userDetailService.loadUser(guiguPickUser);

        if(!guiguPasswordEncoder.matches(userDetails.getEncryptedType(),guiguPickUser.getPassword(),userDetails.getPassword())){
            log.debug("Failed to authenticate since password does not match stored value");
            throw new BadCredentialsException("密码不正确");
        }

        userDetails.setLoginType(guiguPickUser.getLoginType());
        userDetails.setPassword("*************");
        return GuiguUsernamePasswordAuthenticationToken.authenticated(userDetails,userDetails.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return GuiguUsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
